// 初始化页面
async function initProfile() {
    const userInfo = JSON.parse(localStorage.getItem('userInfo'));
    if (!userInfo || userInfo.utype !== 2) {
        window.location.href = '../login.html';
        return;
    }

    try {
        // 获取用户最新信息
        const response = await API.user.getAll();
        const currentUser = response.find(user => user.uid === userInfo.uid);
        
        if (currentUser) {
            // 设置默认头像
            const defaultAvatar = "";

            // 填充用户信息
            document.getElementById('uid').value = currentUser.uid;
            
            // 处理性别选择
            const sexSelect = document.getElementById('sex');
            if (currentUser.sex === null || currentUser.sex === undefined) {
                sexSelect.innerHTML = `
                    <option value="">请选择性别</option>
                    <option value="0">男</option>
                    <option value="1">女</option>
                `;
            } else {
                sexSelect.value = currentUser.sex;
            }

            // 处理年龄
            document.getElementById('age').value = currentUser.age || '';
            
            // 处理头像
            const avatarPreview = document.getElementById('avatarPreview');
            if (currentUser.headphoto) {
                // 如果头像数据不是以 data: 开头，则添加前缀
                if (!currentUser.headphoto.startsWith('data:')) {
                    avatarPreview.src = `data:image/jpeg;base64,${currentUser.headphoto}`;
                } else {
                    avatarPreview.src = currentUser.headphoto;
                }
            } else {
                avatarPreview.src = defaultAvatar;
            }

            // 更新本地存储的用户信息
            localStorage.setItem('userInfo', JSON.stringify(currentUser));
        }

        // 添加头像上传事件
        document.querySelector('.avatar-wrapper').addEventListener('click', () => {
            document.getElementById('avatarInput').click();
        });

        document.getElementById('avatarInput').addEventListener('change', handleAvatarChange);
    } catch (error) {
        console.error('获取用户信息失败:', error);
        alert('获取用户信息失败');
    }
}

// 处理头像更改
async function handleAvatarChange(event) {
    const file = event.target.files[0];
    if (file) {
        try {
            const base64Data = await FileUtils.encodeFile(file);
            document.getElementById('avatarPreview').src = base64Data;
        } catch (error) {
            console.error('头像处理失败:', error);
            alert('头像处理失败');
        }
    }
}

// 保存个人信息
async function saveProfile() {
    const userInfo = JSON.parse(localStorage.getItem('userInfo'));
    const newData = {
        uid: userInfo.uid,
        password: userInfo.password,
        sex: parseInt(document.getElementById('sex').value),
        age: parseInt(document.getElementById('age').value),
        headphoto: document.getElementById('avatarPreview').src,
        utype: userInfo.utype
    };

    try {
        await API.user.update(newData);
        // 更新本地存储的用户信息
        localStorage.setItem('userInfo', JSON.stringify({
            ...userInfo,
            ...newData
        }));
        alert('保存成功');
    } catch (error) {
        console.error('保存失败:', error);
        alert('保存失败');
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', initProfile); 